// (c) 2015 Teresa Holfeld
package com.holfeld.teresa.vocabtrainer.card;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * A TextWatcher that enables the given Button if both the given TextInputs have values.
 *
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class CardTextWatcher implements TextWatcher {

    private Button mSaveButton;
    private List<TextView> mInputs;

    public CardTextWatcher(Button saveButton, TextView... inputs) {
        mSaveButton = saveButton;
        mInputs = new ArrayList<TextView>();
        for (TextView input : inputs) {
            mInputs.add(input);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (inputsHaveValues()) {
            View parent = (View) mSaveButton.getParent();
            parent.setVisibility(View.VISIBLE);
            mSaveButton.setEnabled(true);
        } else {
            mSaveButton.setEnabled(false);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // do nothing here
    }

    @Override
    public void afterTextChanged(Editable s) {
        // do nothing here
    }

    private boolean inputsHaveValues() {
        boolean areAllEmpty = true;
        for (TextView input : mInputs) {
            String inputText = input.getText().toString();
            if (TextUtils.isEmpty(inputText)) {
                areAllEmpty = false;
                break;
            }
        }
        return areAllEmpty;
    }
}
